﻿angular.module('Caltech').controller('poItemController', function ($scope, Restangular, $state, $stateParams, toaster, Constants, $filter, ServicePlaces, ProcessStatusPO) {
    'use strict';

    var defaultModel = {
        customer: {
        },
        poDate: new Date(),
        salesman: Constants.accountInfo,
        tax: 0,
        vat: 0,
        serviceCharges: 0,
        items: [],
        showFullName: false,
        status: 1
    };

    $scope.user = Constants.accountInfo;
    $scope.showFullName = false;

    $scope.newRow = {
        quantity: 1
    };

    if ($stateParams.id) {
        Restangular.one('po', $stateParams.id).get().then(function (model) {
            if (model) {
                $scope.model = model;
            }
        });
    } else if ($stateParams.model) {
        // it's copy mode
        $scope.model = JSON.parse($stateParams.model);
    } else {
        $scope.model = defaultModel;
    }

    $scope.$watch('model.items', function () {
        if ($scope.model && $scope.model.items) {
            $scope.tempTotalPrice = $scope.model.items.reduce(function (previousValue, item) {
                return previousValue + (item.quantity * item.unitPrice);
            }, 0);

            $scope.totalAmount = $scope.model.items.reduce(function (previousValue, item) {
                return previousValue + item.quantity;
            }, 0);
        }

    }, true);

    $scope.getCustomerList = function (name) {
        return Restangular.all('customer').getList({
            name: name
        });
    };

    $scope.getEquipmentList = function (model) {
        return Restangular.all('equipment').getList({
            model: model
            //customerId: $scope.model.company.id
        });
    };

    $scope.$watchCollection('[tempTotalPrice, model.serviceCharges]', function () {
        if ($scope.model) {
            $scope.totalPrice = $scope.tempTotalPrice + $scope.model.serviceCharges;
        }
    });

    $scope.$watchCollection('[totalPrice, model.tax]', function () {
        if ($scope.model) {
            $scope.grandTotalItems = Math.round($scope.totalPrice * (1 + $scope.model.tax / 100));
        }
    });

    $scope.$watchCollection('[model.exchangeRate, grandTotalItems]', function () {
        if ($scope.model) {
            $scope.grandTotal = Math.round($scope.grandTotalItems / $scope.model.exchangeRate);
        }
    });

    $scope.$watchCollection('[model.vat, totalVat]', function () {
        if ($scope.model) {
            $scope.totalVat = $scope.totalPrice * ($scope.model.vat / 100);
            $scope.grandTotalItems = $scope.totalPrice + $scope.totalVat;
        }
    });

    $scope.update = function (model) {
        model.companyId = model.company.id;
        model.company = undefined;

        model.salesmanId = model.salesman.id;
        model.salesman = undefined;
        model.updatedBy = Constants.accountInfo.id;
        return model.put().then(function () {
            $state.forceReload();
        });
    };

    $scope.save = function (model) {
        model.companyId = model.company ? model.company.id : 0;
        model.company = undefined;

        model.salesmanId = model.salesman ? model.salesman.id : 0;
        model.salesman = undefined;
        model.createdBy = Constants.accountInfo.id;
        return Restangular.all('po').post(model).then(function () {
            $state.go('po');
        });
    };

    $scope.remove = function (model) {
        return model.remove().then(function () {
            history.back();
        });
    };

    $scope.removeRow = function (index) {
        $scope.model.items.splice(index, 1);
    };

    $scope.copy = function () {
        var model = Restangular.stripRestangular($scope.model);

        toaster.pop('info', "Info", 'Prepared a copy version of po no. ' + model.poNumber);

        model.id = undefined;
        model.poNumber = undefined;
        model.salesman = Constants.accountInfo;

        $state.go('po-new', {
            model: JSON.stringify(model)
        });
    };

    $scope.addRow = function (model) {
        var newRow = angular.copy(model);

        $scope.model.items.push(newRow);

        model.poNumber = undefined;
        model.name = undefined;
        model.manufacturer = undefined;
        model.modelNumber = undefined;
        model.serialNumber = undefined;
        model.servicePlace = 1;
        model.quantity = 1;
        model.unitPrice = undefined;
        model.description = undefined;
    };

    $scope.updateCustomer = function (customer) {
        if (!customer) {
            $scope.model.company = {};
        } else if (typeof (customer) === 'object') {
            $scope.model.company = customer;
        }
    };

    $scope.updatePoItem = function (equipment, target) {
        if (!equipment) {
            target = {};
        } else if (typeof (equipment) === 'object') {
            target.poNumber = equipment.poNumber;
            target.name = equipment.name;
            target.manufacturer = equipment.manufacturer;
            target.modelNumber = equipment.modelNumber;
            target.serialNumber = equipment.serialNumber;
            target.servicePlace = 1;
            target.equipmentId = equipment.id;
            target.unitPrice = equipment.price;
            target.description = equipment.description;
        }
    };


    $scope.getQuoteList = function (poNumber) {
        return Restangular
            .all('quote').getList({
                quoteNumber: poNumber
            });
    };

    $scope.updateEquipment = function (item) {
        var model = $scope.model;

        if (typeof (item) === 'object') {
            model.quoteNumber = item.quoteNumber;

            Restangular.one('customer', item.companyId)
                .get()
                .then(function (customer) {
                    model.company = customer;
                });

            Restangular.one('user', item.salesmanId)
               .get()
               .then(function (user) {
                   model.salesman = user;
               });

            Restangular.one('quote', item.id)
              .get()
              .then(function (quote) {
                  model.items = quote.items;
                  model.tax = quote.tax;
                  model.vat = quote.vat;
                  model.serviceCharges = quote.serviceCharges;
                  model.exchangeRate = quote.exchangeRate;
              });
        }
    };


    $scope.servicePlaces = ServicePlaces.map(function (value) {
        var ordinal = $filter('ordinal');
        value.text = ordinal(value.text).replace('K L', 'KL');
        return value;
    });

    $scope.showServicePlaces = function (value) {
        var result = '';

        if (value) {
            var selected = $filter('filter')($scope.servicePlaces, { value: value });

            if (selected.length) {
                result = selected[0].text;
            }
        }

        return result;
    };

    $scope.status = ProcessStatusPO.map(function (value) {
        var ordinal = $filter('ordinal');
        value.text = ordinal(value.text);
        return value;
    });

    $scope.showStatus = function (value) {
        var result = '';
        if (value) {
            var selected = $filter('filter')($scope.status, { value: value });
            if (selected.length) {
                result = selected[0].text;
            }
        }
        return result;
    };


    if ($stateParams.quoteId > 0) {
        $scope.model.quoteId = $stateParams.quoteId;
        Restangular.one('quote', $stateParams.quoteId).get().then(function (item) {
            $scope.updateEquipment(item);
        });
    }

    $scope.createWO = function (poId) {
        $state.go('workOrder-new', { poId: poId });
    };
});